package com.lcz.mytest.fragment;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lcz.mytest.R;
import com.lcz.mytest.adapter.StockListAdapter;
import com.lcz.mytest.db.StockAPI;
import com.lcz.mytest.domain.StockList;
import com.lcz.mytest.utils.ViewUtils;
import com.lcz.mytest.widget.CustomProgressDialog;

import net.tsz.afinal.http.AjaxCallBack;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    public static final int STATE_UNKOWN = 0;
    public static final int STATE_LOADING = 1;
    public static final int STATE_ERROR = 2;
    public static final int STATE_EMPTY = 3;
    public static final int STATE_SUCCESS = 4;
    public static int state = STATE_UNKOWN;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (frameLayout == null) { // 之前的frameLayout 已经记录了一个爹了 爹是之前的ViewPager
            frameLayout = new FrameLayout(getActivity());
            init(); // 在FrameLayout中 添加不同的界面
        } else {
            ViewUtils.removeParent(frameLayout);// 移除frameLayout之前的爹
        }
        show();// 根据服务器的数据 切换状态

        return frameLayout; // 拿到当前viewPager 添加这个framelayout
    }

    private View loadingView;// 加载中的界面
    private View errorView;// 错误界面
    private View emptyView;// 空界面
    private View successView;// 加载成功的界面
    private FrameLayout frameLayout;
    private View view_SZAll;
    private PullToRefreshListView sz_listview;
    private int page = 1;
    private List<StockList.ResultBean.DataBean> listData = new ArrayList<>();
    private StockListAdapter adapter;
    private CustomProgressDialog loading_dialog;

    // 在FrameLayout中 添加几种不同的界面
    private void init() {
        loadingView = createLoadingView(); // 创建了加载中的界面
        if (loadingView != null) {
            frameLayout.addView(loadingView, new FrameLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        }
        errorView = createErrorView(); // 加载错误界面
        if (errorView != null) {
            frameLayout.addView(errorView, new FrameLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        }
        emptyView = createEmptyView(); // 加载空的界面
        if (emptyView != null) {
            frameLayout.addView(emptyView, new FrameLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        }
        showPage();// 根据不同的状态显示不同的界面
    }

    // 根据不同的状态显示不同的界面
    private void showPage() {
        if (loadingView != null) {
            loadingView.setVisibility(state == STATE_UNKOWN
                    || state == STATE_LOADING ? View.VISIBLE : View.INVISIBLE);
        }
        if (errorView != null) {
            errorView.setVisibility(state == STATE_ERROR ? View.VISIBLE
                    : View.INVISIBLE);
        }
        if (emptyView != null) {
            emptyView.setVisibility(state == STATE_EMPTY ? View.VISIBLE
                    : View.INVISIBLE);
        }
        if (state == STATE_SUCCESS) {
            successView = createSuccessView();
            if (successView != null) {
                frameLayout.addView(successView, new FrameLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                successView.setVisibility(View.VISIBLE);
            }
        }
    }

    private View createSuccessView() {
        final View view = View.inflate(getActivity(), R.layout.sz_list, null);
        sz_listview = (PullToRefreshListView) view.findViewById(R.id.sz_listview);
        sz_listview.setMode(PullToRefreshBase.Mode.BOTH);
        showList(page);
        sz_listview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                showList(page);
            }

            //上拉加载
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                page++;
                showList(page);
            }
        });
        return view;
    }

    private void showList(final int page) {
        AjaxCallBack callBack = new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                System.out.println(result);
                Gson gson = new Gson();
                StockList szList = gson.fromJson(result, StockList.class);
                List<StockList.ResultBean.DataBean> list = szList.getResult().getData();
                if (list != null) {
                    upData(list);
                    sz_listview.onRefreshComplete();//刷新完成
                    loading_dialog.dismiss();
                } else {
                    Toast.makeText(getActivity(), "加载数据失败", Toast.LENGTH_SHORT).show();
                }
                System.out.println(gson.toJson(szList));
            }
        };
        loading_dialog = new CustomProgressDialog(getActivity(), "加载中");
        loading_dialog.show();
        StockAPI.getSZAll(page, callBack);
    }

    //页面更新处理
    private void upData(List<StockList.ResultBean.DataBean> list) {
        if (page == 1) {
            listData.clear();//下拉刷新时清空
        }
        listData.addAll(list);
        if (adapter == null) {
            adapter = new StockListAdapter(listData, getActivity());
            sz_listview.setAdapter(adapter);
        } else {
            adapter.upDataList(listData);
            adapter.notifyDataSetChanged();
        }
    }

    public enum LoadResult {
        error(2), empty(3), success(4);

        int value;

        LoadResult(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }

    }

    // 根据服务器的数据 切换状态
    private void show() {
        if (state == STATE_ERROR || state == STATE_EMPTY) {
            state = STATE_LOADING;
        }
        // 请求服务器 获取服务器上数据 进行判断
        // 请求服务器 返回一个结果
        new Thread() {
            public void run() {
                SystemClock.sleep(2000);
                final LoadResult result = load();
                if (getActivity() != null) {
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (result != null) {
                                state = result.getValue();
                                showPage(); // 状态改变了,重新判断当前应该显示哪个界面
                            }
                        }
                    });
                }
            }

            ;
        }.start();
        showPage();

    }

    private LoadResult load() {

        return LoadResult.success;
    }

    /* 创建了空的界面 */
    private View createEmptyView() {
        View view = View.inflate(getActivity(), R.layout.loadpage_empty, null);
        return view;
    }

    /* 创建了错误界面 */
    private View createErrorView() {
        View view = View.inflate(getActivity(), R.layout.loadpage_error, null);
        Button page_bt = (Button) view.findViewById(R.id.page_bt);
        page_bt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                show();
            }
        });
        return view;
    }

    /* 创建加载中的界面 */
    private View createLoadingView() {
//        View view = null;
        View view = View.inflate(getActivity(), R.layout.loadpage_loading, null);
        return view;
    }

}
